package jssia.database.mysql.columns;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EnumColumn <T extends Enum<T>> extends EnumBackedColumn<T> {

    public EnumColumn(Class<T> enumType) {
        super(enumType);
    }

    public T get(ResultSet rs) throws SQLException {
        final String value = rs.getString(fullyQualifiedName);
        return (value == null || value == "") ? null : Enum.valueOf(enumType, value.toUpperCase());
    }

    public String getString(ResultSet rs) throws SQLException {
        return rs.getString(fullyQualifiedName);
    }

    public void set(PreparedStatement ps, int index, String enumValue) throws SQLException {
        final T t = Enum.valueOf(enumType, enumValue.toUpperCase());
        set(ps, index, t);
    }

    public void setIgnore(PreparedStatement ps, int index, String enumValue) throws SQLException {
        String value = null;
        try {
            value = Enum.valueOf(enumType, enumValue.toUpperCase()).toString();
        } catch(IllegalArgumentException iae) {
        }
        ps.setString(index, value);
    }

    public void set(PreparedStatement ps, int index, T t) throws SQLException {
        ps.setString(index, t.toString());
    }
}
